package com.imoblife.brainwavestus.users;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.protocol.HTTP;

import com.imoblife.brainwavestus.BaseActivity;
import com.imoblife.brainwavestus.R;
import com.imoblife.brainwavestus.customview.BasicDisplay;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem.OBAwardPointsNotifier;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem.OBSpendPointsNotifier;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class UserSignUpActivity extends BaseActivity {

	public static final String TAG = "UserSignUpActivity";
	ProgressDialog dialog;
	BasicDisplay basicDisplay;
	String gmail;
	UserAccount user;
	UsersUtil util;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		basicDisplay = new BasicDisplay(this);

		if (basicDisplay.isXLargerScreen()) {
			setContentView(R.layout.tb_register_layout);
		} else {
			setContentView(R.layout.register_layout);
		}

		user = new UserAccount(this);
		util = new UsersUtil(this);
		gmail = this.getIntent().getStringExtra("gmail").toString();
		init();
	}

	void init() {

		TextView gmailText = (TextView) findViewById(R.id.gmail_text);
		gmailText.setText(gmail);
		final EditText userName = (EditText) findViewById(R.id.user_name);
		Button register = (Button) findViewById(R.id.register);
		register.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String name = userName.getText().toString().trim();
				// new SignUpAsyncTask().execute(gmail, name, util.getIMEI());
				SignUpTask(gmail, name, util.getIMEI());
			}
		});

		TextView url = (TextView) findViewById(R.id.privacy_policy);
		url.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				startActivity(new Intent(
						Intent.ACTION_VIEW,
						Uri.parse("http://mobi.downloadandroid.info/privacy-policy.php")));
			}
		});

	}

	public void SignUpTask(final String gmail, String name, String imei) {
		handler.sendEmptyMessage(2);
		String encodeName = null;
		try {
			encodeName = URLEncoder.encode(name, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		final String urlPath = HttpServerConnectionUtil.REGISTER_PATH
				+ "?gmail=" + gmail + "&name=" + encodeName + "&imei=" + imei;
		new Thread(new Runnable() {
			public void run() {
				try {
					URL url = new URL(urlPath);
					HttpURLConnection connection = (HttpURLConnection) url
							.openConnection();
					connection.setConnectTimeout(10000);
					connection.setReadTimeout(10000);
					connection.setRequestProperty("Charset", "UTF-8");
					connection.connect();
					if (connection.getResponseCode() == 200) {
						BufferedReader br = new BufferedReader(
								new InputStreamReader(connection
										.getInputStream(), HTTP.UTF_8));
						StringBuilder builder = new StringBuilder();
						String line = null;
						while ((line = br.readLine()) != null) {
							builder.append(line);
						}
						String response = builder.toString();
						Log.v(TAG, "response = " + response);
						switch (Integer.parseInt(response)) {
						case 1:
							// new LoginAsyncTask().execute(gmail);
							loginTask(gmail);
							break;
						case 2:
							handler.sendEmptyMessage(1);
							Looper.prepare();
							Toast.makeText(
									UserSignUpActivity.this,
									getStringResource(R.string.register_error_code_response),
									3000).show();
							Looper.loop();
							break;
						case 3:
							handler.sendEmptyMessage(1);
							Looper.prepare();
							Toast.makeText(
									UserSignUpActivity.this,
									getStringResource(R.string.Illegal_parameter_massger),
									3000).show();
							Looper.loop();
							break;
						case 4:
							handler.sendEmptyMessage(1);
							Looper.prepare();
							Toast.makeText(
									UserSignUpActivity.this,
									getStringResource(R.string.register_fail_titlt),
									3000).show();
							UserSignUpActivity.this.finish();
							Looper.loop();
							break;
						default:
							break;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(1);
					Looper.prepare();
					Toast.makeText(
							UserSignUpActivity.this,
							getStringResource(R.string.register_error_code_response),
							3000).show();
					UserSignUpActivity.this.finish();
					Looper.loop();
				}
			}
		}).start();
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				dialog.cancel();
				break;
			case 2:
				dialog = new ProgressDialog(UserSignUpActivity.this) {
					protected void onStop() {
						dialog = null;
						super.onStop();
					}
				};
				dialog.setMessage(getStringResource(R.string.doing));
				dialog.setCanceledOnTouchOutside(false);
				dialog.setCancelable(false);
				dialog.show();
				break;
			default:
				break;
			}
		}

	};

	public void loginTask(final String gmail) {
		OBpurchaseSystem.getOBpurchaseSystem(this).getTapPoints2();
		new Thread(new Runnable() {
			public void run() {
				String urlPath = HttpServerConnectionUtil.LOGIN_PATH
						+ "?gmail=" + gmail;
				try {
					URL url = new URL(urlPath);
					HttpURLConnection connection = (HttpURLConnection) url
							.openConnection();
					connection.setConnectTimeout(10000);
					connection.setReadTimeout(10000);
					connection.setRequestProperty("Charset", "UTF-8");
					connection.connect();
					if (connection.getResponseCode() == 200) {
						BufferedReader br = new BufferedReader(
								new InputStreamReader(connection
										.getInputStream(), HTTP.UTF_8));
						StringBuilder builder = new StringBuilder();
						String line = null;
						while ((line = br.readLine()) != null) {
							builder.append(line);
						}
						String response = builder.toString();
						if (response.equals("2")) {
							handler.sendEmptyMessage(1);
							UserSignUpActivity.this.finish();
							Looper.prepare();
							Toast.makeText(
									UserSignUpActivity.this,
									getStringResource(R.string.register_suc),
									3000).show();
							Looper.loop();
						} else {
							try {
								String[] userInfo = response.split("\\|");
								user.setGmail(gmail);
								user.setName(userInfo[0]);
								user.setGold(userInfo[1]);
								user.setStatus(userInfo[2]);
								user.setIsLogin(true);
								Log.d(TAG,
										"ע��ɹ����¼ʱ��tapjoy���ؽ�� = "
												+ OBpurchaseSystem
														.getOBpurchaseSystem(
																UserSignUpActivity.this)
														.getTapjoyPoints() );
								if (OBpurchaseSystem.getOBpurchaseSystem(
										UserSignUpActivity.this)
										.getTapjoyPoints() > 0) {
									OBpurchaseSystem
											.getOBpurchaseSystem(
													UserSignUpActivity.this)
											.spendTapPoints(
													OBpurchaseSystem
															.getOBpurchaseSystem(
																	UserSignUpActivity.this)
															.getTapjoyPoints(),
													new OBLoginSpendTapPointsImpl());
								} else {
									Intent intent = new Intent(
											UsersUtil.UPDATE_STATEVIEW_UI);
									intent.putExtra(
											"updateCode",
											UsersUtil.UPDATE_STATEVIEW_USERCENTER);
									UserSignUpActivity.this
											.sendBroadcast(intent);
									handler.sendEmptyMessage(1);
									UserSignUpActivity.this.finish();
									OBpurchaseSystem
											.getOBpurchaseSystem(
													UserSignUpActivity.this)
											.awardTapPoints(
													Integer.parseInt(user
															.getGold()),
													new OBAwardTapjoyPointsNotifyImpl());
								}
							} catch (Exception e) {
								util.setIsAwardSuccess(UserSignUpActivity.this,
										false);
								e.printStackTrace();
								handler.sendEmptyMessage(1);
								Looper.prepare();
								Toast.makeText(
										UserSignUpActivity.this,
										getStringResource(R.string.register_suc),
										3000).show();
								Looper.loop();
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					util.setIsAwardSuccess(UserSignUpActivity.this, false);
					handler.sendEmptyMessage(1);
					Looper.prepare();
					Toast.makeText(
							UserSignUpActivity.this,
							getStringResource(R.string.register_error_code_response),
							3000).show();
					Looper.loop();
				}
			}
		}).start();
	}

	public class OBAwardTapjoyPointsNotifyImpl implements OBAwardPointsNotifier {

		public void getAwardPointsResponse(String currencyName, int pointTotal) {
			util.setIsAwardSuccess(UserSignUpActivity.this, true);
			Looper.prepare();
			Toast.makeText(UserSignUpActivity.this,
					getStringResource(R.string.register_suc), 3000).show();
			Looper.loop();

		}

		public void getAwardPointsResponseFailed(String error) {
			util.setIsAwardSuccess(UserSignUpActivity.this, false);
			Looper.prepare();
			Toast.makeText(UserSignUpActivity.this,
					getStringResource(R.string.register_suc), 3000).show();
			Looper.loop();
		}
	}

	public class OBLoginSpendTapPointsImpl implements OBSpendPointsNotifier {
		public void getSpendPointsResponse(String currencyName, int pointTotal) {
			Intent intent = new Intent(UsersUtil.UPDATE_STATEVIEW_UI);
			intent.putExtra("updateCode", UsersUtil.UPDATE_STATEVIEW_USERCENTER);
			UserSignUpActivity.this.sendBroadcast(intent);
			handler.sendEmptyMessage(1);
			UserSignUpActivity.this.finish();
			OBpurchaseSystem.getOBpurchaseSystem(UserSignUpActivity.this)
					.awardTapPoints(Integer.parseInt(user.getGold()),
							new OBAwardTapjoyPointsNotifyImpl());
		}

		public void getSpendPointsResponseFailed(String error) {
			util.setIsAwardSuccess(UserSignUpActivity.this, false);
			handler.sendEmptyMessage(1);
			UserSignUpActivity.this.finish();
			Looper.prepare();
			Toast.makeText(UserSignUpActivity.this,
					getStringResource(R.string.user_login_fail), 3000).show();
			Looper.loop();
		}

	}

	public String getStringResource(int id) {
		return this.getResources().getString(id);
	}

	public void showToast(String info) {
		Looper.prepare();
		Toast.makeText(this, info, 3000).show();
		Looper.loop();
	}

	@Override
	public void onImgHomeClicked(View v) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTitleMenuClicked(View v) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSubScriptionClicked(View v) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onMySubScriptionClicked(View v) {
		// TODO Auto-generated method stub
		
	}
}
